<template>
  <view class="mine-info-container">
    <e-navbar left-title="个人资料"></e-navbar>
    <u-gap height="15"></u-gap>
    <view class="main-card mine-info-card">
      <view class="cell-item">
        <view class="label">头像</view>
        <view class="value">
          <!-- #ifdef MP-WEIXIN -->
					<button class="u-reset-button" style="margin: 0;" open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
					  <u-avatar v-if="mineInfo.avatar == ''" :src="$image(default_avatar)" size="61" @click="handleChooseImage()"></u-avatar>
					  <u-avatar v-else :src="$image(mineInfo.avatar,'yes')" size="61" @click="handleChooseImage()"></u-avatar>
					</button>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
					<avatar
							selWidth="200px" selHeight="400upx" @upload="myUpload" :avatarSrc="$image(mineInfo.avatar,'yes')"
							avatarStyle="width: 122rpx; height: 122rpx; border-radius: 100%;">
					</avatar>
          <!-- #endif -->
				<view class="m-l-16">
					<u-icon name="arrow-right" size="10" color="#999999"></u-icon>
				</view>
        </view>
      </view>
    </view>
    <u-gap height="8"></u-gap>
    <view class="main-card mine-info-card" style="padding: 0">
      <view class="cell-item p-30">
        <view class="label">昵称</view>
        <view class="value" @click="handleCellItem('nickname')">
          <view>{{mineInfo.nickname || "未设置"}}</view>
          <u-icon name="arrow-right" size="10" color="#999999"></u-icon>
        </view>
      </view>
      <view class="cell-item p-30">
        <view class="label">手机号</view>
        <view class="value">
          <button
              v-if="!mineInfo.telephone"
              class="u-reset-button"
              style="color: #007aff;margin: 0"
              open-type="getPhoneNumber"
              @getphonenumber="getPhoneNumber"
          >授权手机号</button>
          <view v-else>
            {{mineInfo.telephone || "未设置"}}
          </view>
        </view>
      </view>
      <view class="cell-item p-30">
        <view class="label">性别</view>
        <view class="value">
          <view class="flex col-center row-right">
            <u-radio-group
                v-model="mineInfo.gender"
                placement="row"
                @change="groupChange"
            >
              <u-radio
                  :customStyle="{marginLeft: '8px'}"
                  v-for="(item, idx) in radiolist"
                  :key="idx"
                  :label="item.name"
                  :name="item.name"
              >
              </u-radio>
            </u-radio-group>
          </view>
        </view>
      </view>
      <view class="cell-item p-30">
        <view class="label">出生年月时辰</view>
        <view class="value" @click="handleCellItem('birthday')">
          <view>{{formatBrithday || "请选择出生年月"}}</view>
          <u-icon name="arrow-right" size="10" color="#999999"></u-icon>
        </view>
      </view>
      <view class="cell-item p-30">
        <view class="label">出生地点</view>
        <view class="value">
          <uni-data-picker
              :localdata="localdata"
              popup-title="出生地点"
              placeholder="请选择出生地点"
              :map="{text:'ext_name',value:'id'}"
              v-model="mineInfo.birthplace_id"
              @change="onChangeArea"
              @nodeclick="onNodeclickArea"
              v-slot:default="{data, error, options}"
              :clear-icon="false">
              <view class="flex col-center row-right">
                <view v-if="error" class="error">
                  <text>{{error}}</text>
                </view>
                <view v-else-if="areaAddress.length" class="selected text-right">
                  <text v-for="(item,index) in areaAddress" :key="index">{{item.text}}</text>
                </view>
                <view class="placeholder-text font-26 text-right" v-else>
                  <text>请选择出生地点</text>
                </view>
                <view class="m-l-16">
                  <u-icon name="arrow-right" size="10" color="#999999"></u-icon>
                </view>
              </view>
          </uni-data-picker>
        </view>
      </view>
      <view class="cell-item p-30">
        <view class="label">现居地址</view>
        <view class="value">
          <uni-data-picker
            :localdata="localdata"
            popup-title="现居地址"
            placeholder="请选择现居地址"
            :map="{text:'ext_name',value:'id'}"
            v-model="mineInfo.current_address_id"
            @change="onChangeNowArea"
            @nodeclick="onNodeclickNowArea"
            v-slot:default="{data, error, options}"
            :clear-icon="false">
            <view class="flex col-center row-right">
              <view v-if="error" class="error">
                <text>{{error}}</text>
              </view>
              <view v-else-if="nowAreaAddress.length > 0" class="selected text-right">
                <text v-for="(item,index) in nowAreaAddress" :key="index">{{item.text}}</text>
              </view>
              <view class="placeholder-text font-26 text-right" v-else>
                <text>请选择现居地址</text>
              </view>
              <view class="m-l-16">
                <u-icon name="arrow-right" size="10" color="#999999"></u-icon>
              </view>
            </view>
          </uni-data-picker>
        </view>
      </view>
      <!--<view class="cell-item p-30" v-for="(key,index) in Object.keys(mineInfo)" :key="index" v-if="key != 'area_id' && key != 'nowarea_id'">-->
      <!--  <view class="label">{{getTitle(key)}}</view>-->
      <!--  <template v-if="key != 'sex' && key != 'area' && key != 'nowarea' && key != 'year'">-->
      <!--    <view class="value" @click="handleCellItem(key)">-->
      <!--      <view class="hidden_one" v-if="key == 'birthday'">{{mineInfo[key] == "" ? "请选择出生日期" : mineInfo[key]}}</view>-->
      <!--      <view class="hidden_one" v-else>{{mineInfo[key]}}</view>-->
			<!--			<view class="m-l-16" v-if="key == 'mobile' && mineInfo[key] == ''">-->
			<!--				<button class="u-reset-button" style="color: #007aff;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权手机号</button>-->
			<!--			</view>-->
      <!--      <view class="m-l-16" v-if="key != 'mobile'">-->
      <!--        <u-icon name="arrow-right" size="10" color="#999999"></u-icon>-->
      <!--      </view>-->
      <!--    </view>-->
      <!--  </template>-->
      <!--  <template v-else-if="key == 'area'">-->
      <!--    <view class="value">-->
			<!--			<uni-data-picker-->
			<!--			    :localdata="localdata"-->
			<!--			    popup-title="出生地点"-->
			<!--			    placeholder="请选择出生地点"-->
			<!--			    :map="{text:'ext_name',value:'id'}"-->
			<!--			    v-model="mineInfo.area_id"-->
			<!--			    @change="onChangeArea"-->
			<!--			    @nodeclick="onNodeclickArea"-->
			<!--			    v-slot:default="{data, error, options}"-->
			<!--			    :clear-icon="false">-->
			<!--			    <view v-if="error" class="error">-->
			<!--			      <text>{{error}}</text>-->
			<!--			    </view>-->
			<!--			    <view v-else-if="areaAddress.length" class="selected">-->
			<!--			      <text v-for="(item,index) in areaAddress" :key="index">{{item.text}}</text>-->
			<!--			    </view>-->
			<!--			    <view class="placeholder-text" v-else>-->
			<!--			      <text>请选择出生地点</text>-->
			<!--			    </view>-->
			<!--			</uni-data-picker>-->
			<!--			-->
      <!--      <view class="m-l-16">-->
      <!--        <u-icon name="arrow-right" size="10" color="#999999"></u-icon>-->
      <!--      </view>-->
      <!--    </view>-->
      <!--  </template>-->
			<!--	<template v-else-if="key == 'nowarea'">-->
			<!--	  <view class="value">-->
			<!--			<uni-data-picker-->
			<!--			    :localdata="localdata"-->
			<!--			    popup-title="现居地址"-->
			<!--			    placeholder="请选择现居地址"-->
			<!--			    :map="{text:'ext_name',value:'id'}"-->
			<!--			    v-model="mineInfo.nowarea_id"-->
			<!--			    @change="onChangeNowArea"-->
			<!--			    @nodeclick="onNodeclickNowArea"-->
			<!--			    v-slot:default="{data, error, options}"-->
			<!--			    :clear-icon="false">-->
			<!--			    <view v-if="error" class="error">-->
			<!--			      <text>{{error}}</text>-->
			<!--			    </view>-->
			<!--			    <view v-else-if="nowAreaAddress.length > 0" class="selected">-->
			<!--			      <text v-for="(item,index) in nowAreaAddress" :key="index">{{item.text}}</text>-->
			<!--			    </view>-->
			<!--			    <view class="placeholder-text" v-else>-->
			<!--			      <text>请选择现居地址</text>-->
			<!--			    </view>-->
			<!--			</uni-data-picker>-->
			<!--			-->
			<!--	    <view class="m-l-16">-->
			<!--	      <u-icon name="arrow-right" size="10" color="#999999"></u-icon>-->
			<!--	    </view>-->
			<!--	  </view>-->
			<!--	</template>-->
      <!--  <template v-else>-->
      <!--    <view class="value">-->
      <!--      <view class="flex col-center row-right">-->

      <!--        <u-radio-group-->
      <!--            v-model="mineInfo.sex"-->
      <!--            placement="row"-->
      <!--            @change="groupChange"-->
      <!--        >-->
      <!--          <u-radio-->
      <!--              :customStyle="{marginLeft: '8px'}"-->
      <!--              v-for="(item, idx) in radiolist"-->
      <!--              :key="idx"-->
      <!--              :label="item.name"-->
      <!--              :name="item.name"-->
      <!--          >-->
      <!--          </u-radio>-->
      <!--        </u-radio-group>-->
      <!--      </view>-->
      <!--    </view>-->
      <!--  </template>-->
      <!--</view>-->
    </view>
    <u-gap height="60"></u-gap>
    <!--<view class="main-btn m-30">-->
    <!--  <u-button text="退出登录" color="#1F66FF" @click="handleLogOut"></u-button>-->
    <!--</view>-->
    <e-popup ref="editNickname" title="修改昵称" @close="handleClosePopup" @confirm="handleConfirmPopup">
      <view class="popup-cell" slot="content" >
        <view class="cell-item">
					<input type="nickname" v-model="nicknameValue" placeholder="请输入需要修改的昵称" placeholder-class="placeholder-class" />
          <!-- <u-input v-model="nicknameValue" placeholder="请输入需要修改的昵称" border="none"></u-input> -->
        </view>
      </view>
    </e-popup>
    <e-popup ref="logout" title="退出登录" @close="handleClosePopup" @confirm="handleConfirmPopup"></e-popup>
    <u-datetime-picker
        ref="datePicker"
        :show="dateShow"
        :minDate="minDate"
        :maxDate="maxDate"
        :closeOnClickOverlay="true"
        v-model="dataValue"
        mode="datetime"
        @close="handleCloseDatePicker"
        @cancel="handleCloseDatePicker"
        @confirm="handleConfirmDatePicker"
    ></u-datetime-picker>
    <!--<u-picker-->
    <!--    :show="showShichen"-->
    <!--    :columns="shichenColumns"-->
    <!--    :closeOnClickOverlay="true"-->
    <!--    @close="handleCloseShichen"-->
    <!--    @cancel="handleCloseShichen"-->
    <!--    @confirm="handleConfirmShichen"-->
    <!--&gt;</u-picker>-->
  </view>
</template>

<script>
let app = getApp();
import config from '@/common/config'
import avatar from "@/components/yq-avatar/yq-avatar.vue";
import { formatDate ,getCalendarDate } from "@/common/utils"
export default {
  components: {
    avatar
  },
  data() {
    return {
			default_avatar: "/images/default-avatar.png",
      user_avatar: "",
			localdata: [],
      mineInfo: {
        avatar: "", // 头像
        nickname: "", // 昵称
        telephone: "", // 手机号
        gender: "", // 0:女，1：男
        birthday: "", // 出生年月时辰
        birthplace: "", // 出生地址
        birthplace_id: "", // 出生地址id
        current_address: "", // 现居地址
        current_address_id: "", // 现居地址id
      },
      radiolist: [{
          name: "男",
        },
        {
          name: "女",
        }
      ],
      nicknameValue: "",
      popupType: "",
      dateShow: false,
      minDate: new Date(1950, 1, 1).getTime(),
      maxDate: new Date().getTime(),
      dataValue: "",
      join_date: "",  //  拼接年月日 + 时辰
      showShichen: false,
      shichenColumns: [
        [
          "子时",
          "丑时",
          "寅时",
          "卯时",
          "辰时",
          "巳时",
          "午时",
          "未时",
          "申时",
          "酉时",
          "戌时",
          "亥时"
        ]
      ],
			useType: "", //进入的type类型  cesuan = 从流年测算页面进入
			areaAddress:[],
			nowAreaAddress:[],
      formatBrithday: "", // 格式化出生日期
    }
  },
  computed: {
    getTitle() {
      return function(key){
        const titleMap = {
          nickname: "昵称",
          mobile: "手机号",
          sex: "性别",
          birthday: "出生年月",
          area: "出生地点",
          nowarea: "现居地址",
        };
        return titleMap[key] || key; // 返回映射的中文标题，如果没有映射则返回原键
      }
    }
  },
	onLoad(options) {
		this.getUserInfo();
		this.getLocaldata().then(res => {
		  this.localdata = res;
		});
	},
  methods: {
		getLocaldata() {
		  return new Promise((resolve, reject) => {
		    uni.request({
		      url: config.imageUrl + '/area_format_user.json',
		      success: (res) => {
		        resolve(res.data);
		      },
		      fail: (err) => {
		        reject(err);
		      }
		    });
		  });
		},
		// 授权手机号
		async getPhoneNumber(e) {
		  uni.showLoading({
		    title: '授权中',
		    mask: true
		  });
		  if(e.target.errMsg === 'getPhoneNumber:ok'){
		    console.log(e.target.code);
		    const res = await this.$api.set_mobile({code:e.target.code});
		    console.log(res.data);
		    if(res.code == 1){
          this.getUserInfo();
		      // this.mineInfo.mobile = res.data.mobile;
					// this.editUserInfo('mobile',res.data.mobile);
		    }
		    uni.hideLoading();
		  }else{
		    uni.hideLoading();
		  }
		  console.log(e)
		},
		async handleChooseAvatar(e){
		  console.log(e);
			const res = await this.$api.fileUpload({filePath:e.detail.avatarUrl});
			if(res.code == 1){
        this.mineInfo.avatar = res.data.file_path;
        this.editUserInfo('avatar',res.data.file_path);
			}
		},
		// 选择头像
		handleChooseImage(){
			// uni.chooseImage({
			//   count: 1,
			//   sizeType: ['original', 'compressed'],
			//   sourceType: ['album', 'camera'],
			//   success: async (res) => {
			//     const result = await this.$api.fileUpload2({filePath:res.tempFilePaths[0]});
			//     if(result.code == 0){
			// 			console.log('ddddd',result);
			//     }
			//   }
			// });
			uni.chooseImage({
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					uni.uploadFile({
						url: config.cesuUrl + '/upavatar/', //仅为示例，非真实的接口地址
						filePath: tempFilePaths[0],
						name: 'file',
						formData: {
							id:5
						},
						success: (uploadFileRes) => {
							console.log(uploadFileRes.data);
						}
					});
				}
			});
		},
    async myUpload(rsp) {
			const res = await this.$api.fileUpload({filePath:rsp.path});
			if(res.code == 1){
        this.mineInfo.avatar = res.data.file_path;
        this.editUserInfo('avatar',res.data.file_path);
			}
    },
    groupChange(n) {
			this.editUserInfo('gender',n);
    },
    handleCellItem(key) {
      switch (key) {
        case "nickname": // 修改昵称
          this.popupType = key;
          this.$refs.editNickname.handleShowPopup("修改昵称");
          this.nicknameValue = this.mineInfo.nickname;
          break;
        case "birthday":
          this.$refs.datePicker.innerValue = (this.mineInfo.birthday * 1) || this.maxDate;
          this.dateShow = true;
          break;
      }
    },
    // 取消按钮回调
    handleClosePopup(){
      switch (this.popupType){
        case "nickname":
          this.nicknameValue = "";
          this.$refs.editNickname.handleClosePopup();
          break;
        case "birthday":
          this.dateShow = false;
          break;
        case "logout":
          this.$refs.logout.handleClosePopup();
          break;
      }
      this.popupType = "";
    },
    // 确认按钮回调
    handleConfirmPopup(){
      switch (this.popupType){
        case "nickname":
          if(this.nicknameValue == "") return this.$u.toast("请输入昵称");
					this.editUserInfo(this.popupType,this.nicknameValue);
          break;
        case "logout":
          this.$u.toast("退出成功");
					this.handleClosePopup();
          break;
      }
    },
    // 点击退出登录
    handleLogOut(){
      this.popupType = "logout";
      this.$refs.logout.handleShowPopup("确定退出此账号?");
    },
		// 选择出生地
    onChangeArea(event) {
      // 处理选择变化
			this.areaAddress = event.detail.value;
			let addressStr = this.areaAddress.map(item => item.text).join('/');
			let copyAreaAddress = JSON.parse(JSON.stringify(this.areaAddress));
			let areaLastId = copyAreaAddress.pop().value;
			this.mineInfo.area = areaLastId;
			this.editUserInfo('birthplace_id',areaLastId);
			this.editUserInfo('birthplace',addressStr);
    },
    onNodeclickArea(event) {
      // 处理节点点击
      console.log('onChange', event);
    },
		// 选择居住地
		onChangeNowArea(event) {
		  // 处理选择变化
			this.nowAreaAddress = event.detail.value;
			let addressStr = this.nowAreaAddress.map(item => item.text).join('/');
			let copyNowAreaAddress = JSON.parse(JSON.stringify(this.nowAreaAddress));
			let nowAreaLastId = copyNowAreaAddress.pop().value;

			this.mineInfo.nowarea = nowAreaLastId;
			this.editUserInfo('current_address_id',nowAreaLastId);
			this.editUserInfo('current_address',addressStr);
		},
		onNodeclickNowArea(event) {
		  // 处理节点点击
		  console.log('onChange', event);
		},
    handleCloseDatePicker(){
      this.dateShow = false;
    },
    async handleConfirmDatePicker(event){
      this.dataValue = event.value;
      let date = await getCalendarDate({
				date:this.$u.timeFormat(event.value, 'yyyy-mm-dd hh:MM:ss')
			});
      let year = date.solarDate.split(' ')[0];
      let shichen = date.lunarHour;
      this.formatBrithday = year + " " + shichen;
      this.dateShow = false;
      this.editUserInfo('birthday',this.dataValue);
      // this.showShichen = true;
    },
    handleCloseShichen(){
      this.dataValue = "";
      this.showShichen = false;
    },
    handleConfirmShichen(event) {
      let shichen = formatDate(this.dataValue) + " " + event.value[0];
			let year = shichen.slice(0,4);
			this.editUserInfo('birthday',shichen);
			// this.editUserInfo('year',year);
    },
		// 修改用户信息
		async editUserInfo(key,value){
			const res = await this.$api.set_profile({[key]:value});
			if(res.code == 1){
				// this.$u.toast("修改成功");
				this.mineInfo[key] = value;
				this.handleClosePopup();
				this.handleCloseShichen();
				let userinfo = uni.getStorageSync('userinfo');
				if(userinfo){
					let sucInfo = Object.assign(JSON.parse(userinfo),this.mineInfo)
					uni.setStorageSync('userinfo',JSON.stringify(sucInfo));
				}
			}
		},
		// 获取用户信息
		async getUserInfo(){
      let {
        avatar,
        nickname,
        telephone,
        gender,
        birthday,
        birthplace,
        birthplace_id,
        current_address,
        current_address_id,
      } = await app.getMineInfo();
      Object.assign(this.mineInfo, {
        avatar,
        nickname,
        telephone,
        gender,
        birthday,
        birthplace,
        birthplace_id,
        current_address,
        current_address_id,
      })
      if(birthday){
        let date = await getCalendarDate({
					date:this.$u.timeFormat(birthday, 'yyyy-mm-dd hh:MM:ss')
				});
        let year = date.solarDate.split(' ')[0];
        let shichen = date.lunarHour;
        this.formatBrithday = year + " " + shichen;
      }
      console.log('获取用户信息', this.mineInfo);
			if(birthplace){
				let address = birthplace.split('/');
				this.areaAddress = address.map(item => {
				  return {
				    text:item
				  }
				});
			}
			if(current_address){
				let nowAddress = current_address.split('/');
				this.nowAreaAddress = nowAddress.map(item => {
				  return {
				    text:item
				  }
				})
			}
			console.log('获取用户信息成功', this.areaAddress);
		}
  }
}
</script>

<style lang="scss" scoped>
  .mine-info-container{
    .mine-info-card{
      padding: 30rpx;
      .cell-item:not(:last-child){
        border-bottom: 1px solid #F2F2F2;
      }
      .cell-item,.value{
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .label{
        color: #333333;
        font-size: 26rpx;
      }
      .value{
        color: #999999;
        font-size: 26rpx;
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-left: 30rpx;
      }
    }
  }
</style>
